import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { map } from "rxjs/operators";
import { FetchService } from "../../../core/net/fetch.service";
import * as moment from "moment";
import { NzMessageService, UploadChangeParam, UploadFile } from "ng-zorro-antd";

@Component({
    selector: "app-pm-check",
    templateUrl: "./pm-check.component.html",
    styleUrls: ["./pm-check.component.scss"],
})
export class PmCheckComponent implements OnInit {
    searchForm: FormGroup;
    projectTypeList: Array<{ label: string; value: string | number }>;
    projectTypeMapper;
    statusTypeList: Array<{ label: string; value: string | number }>;
    statusMapper;
    resultTypeList: Array<{ label: string; value: string | number }>;
    resultMapper;
    staffList: Array<{ name: string; id: string | number }>;
    staffMapper;
    projectList: Array<{ name: string; id: string | number }>;
    tableData = [];
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = false;
    checkTableData = [];
    checkForm: FormGroup;
    modalTitle: string = "";
    modalShow: boolean = false;

    modalShowView: boolean = false;
    uploadUrl = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
    uploadUrlVideo = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
    fileList: UploadFile[] = [];
    fileListVideo: UploadFile[] = [];
    fileUploadDisabled = false;
    fileUploadDisabledVideo = false;
    imgSrc = "";
    videoSrc = "";
    showType = "img";
    pieChartOption = {
        tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b} : {c} ({d}%)",
        },
        color: ["#637efe", "#ffc209", "#0094f0", "#d2e2ff"],
        legend: {
            bottom: 0,
            data: [],
        },
        series: [
            {
                type: "pie",
                radius: "55%",
                center: ["50%", "50%"],
                data: [],
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: "rgba(0, 0, 0, 0.5)",
                    },
                },
            },
        ],
    };
    countInfoChartOpt;
    areaInfoChartOpt;
    projectInfoChartOpt;
    errorInfoChartOpt;

    constructor(
        private fb: FormBuilder,
        private message: NzMessageService,
        private fetchService: FetchService
    ) { }

    ngOnInit(): void {
        this.searchForm = this.fb.group({
            rangePickerTime: [
                [moment().subtract(1, "months").startOf("month").valueOf(), new Date()],
            ],
            // objtype: [],
            // state: [],
            // staffid: [],
            // resultstate: []
            keywords: [],
        });
        this.checkForm = this.fb.group({
            taskid: "",
            objid: [null, Validators.required],
            taskname: [null, Validators.required],
            taskdesc: [null, Validators.required],
            staffid: [null, Validators.required],

            // begindate: [new Date()],
            // enddate: [new Date()],
            begindate: [null, Validators.required],
            enddate: [null, Validators.required],
            state: [null, Validators.required],
            resultstate: [null, Validators.required],
            result: [null, Validators.required],
        });
        //  人员列表查询
        this.fetchService
            .post<any>("sys/sysApiInfo/queryApiData", {
                apicode: "15",
                manageId: "1",
            })
            .subscribe((res) => {
                if (Array.isArray(res)) {
                    this.staffList = res;
                    this.staffMapper = this.staffList.reduce((def, item) => {
                        def[item.id] = item.name;
                        return def;
                    }, {});
                }
            });
        //  工程列表查询
        this.fetchService
            .post<any>("archives/wrsProjectInfo/list", {
                pageSize: 10000,
            })
            .subscribe((res) => {
                this.projectList = res["list"] || [];
                this.projectList.forEach((item) => {
                    item.id = item.id + "";
                });
                this.checkTableData = res["list"];
            });
        // 10014 工程类型
        // 10018 工程状态
        // 10019 结果状态
        this.getDictValue("10014").subscribe((res) => {
            this.projectTypeList = res.list;
            this.projectTypeMapper = res.mapper;
        });
        this.getDictValue("10018").subscribe((res) => {
            this.statusTypeList = res.list;
            this.statusMapper = res.mapper;
        });
        this.getDictValue("10019").subscribe((res) => {
            this.resultTypeList = res.list;
            this.resultMapper = res.mapper;
        });

        this.queryInfo();
    }

    getDictValue(typeId) {
        return this.fetchService
            .post<any>("sys/sysDictValue/list", {
                dictTypeId: typeId,
            })
            .pipe(
                map((res) => {
                    const list = res["list"] || [];
                    const mapper = list.reduce((def, item) => {
                        def[item.value] = item.label;
                        return def;
                    }, {});
                    return {
                        list,
                        mapper,
                    };
                })
            );
    }
    handleChange({ file, fileList }: UploadChangeParam): void {
        const status = file.status;
        if (status !== "uploading") {
            console.log(file, fileList);
        }
        if (status === "done") {
            this.message.success(`${file.name} 文件上传成功`);
            this.fileList = fileList;
        } else if (status === "error") {
            this.message.success(`${file.name} 文件上传失败，请重试`);
        }
    }
    handleChangeVideo({ file, fileList }: UploadChangeParam): void {
        const status = file.status;
        if (status !== "uploading") {
            console.log(file, fileList);
        }
        if (status === "done") {
            this.message.success(`${file.name} 文件上传成功`);
            this.fileListVideo = fileList;
        } else if (status === "error") {
            this.message.success(`${file.name} 文件上传失败，请重试`);
        }
    }

    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        this.loading = true;
        const params = {
            ...this.searchForm.value,
            begindate: this.searchForm.get("rangePickerTime").value[0]
                ? moment(this.searchForm.get("rangePickerTime").value[0]).format(
                    "YYYY-MM-DD"
                )
                : null,
            enddate: this.searchForm.get("rangePickerTime").value[1]
                ? moment(this.searchForm.get("rangePickerTime").value[1]).format(
                    "YYYY-MM-DD"
                )
                : null,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
        };
        this.fetchService
            .post("projectManage/xjTask/list", params)
            .subscribe((res) => {
                this.tableData = res["list"];
                this.total = res["total"];
                this.loading = false;
            });
        // this.queryKpiData();
    }

    queryKpiData(): void {
        //  kpi查询
        this.fetchService
            .post<any>("projectManage/xjTask/kpi", {
                begindate: this.searchForm.get("rangePickerTime").value[0]
                    ? moment(this.searchForm.get("rangePickerTime").value[0]).format(
                        "YYYY-MM-DD"
                    )
                    : null,
                enddate: this.searchForm.get("rangePickerTime").value[1]
                    ? moment(this.searchForm.get("rangePickerTime").value[1]).format(
                        "YYYY-MM-DD"
                    )
                    : null,
            })
            .subscribe((res) => {
                this.countInfoChartOpt = {
                    legend: {
                        data: Object.keys(res["countInfo"]),
                    },
                    series: [
                        {
                            name: "执行情况",
                            data: Object.keys(res["countInfo"]).map((key) => {
                                return {
                                    value: res["countInfo"][key],
                                    name: key,
                                };
                            }),
                        },
                    ],
                };
                this.errorInfoChartOpt = {
                    legend: {
                        data: Object.keys(res["errorInfo"]),
                    },
                    series: [
                        {
                            name: "正常异常统计",
                            data: Object.keys(res["errorInfo"]).map((key) => {
                                return {
                                    value: res["errorInfo"][key],
                                    name: key,
                                };
                            }),
                        },
                    ],
                };
                this.projectInfoChartOpt = {
                    legend: {
                        data: Object.keys(res["projectInfo"]),
                    },
                    series: [
                        {
                            name: "故障类型",
                            data: Object.keys(res["projectInfo"]).map((key) => {
                                return {
                                    value: res["projectInfo"][key],
                                    name: key,
                                };
                            }),
                        },
                    ],
                };
                this.areaInfoChartOpt = {
                    legend: {
                        data: Object.keys(res["areaInfo"]),
                    },
                    series: [
                        {
                            name: "异常地区统计",
                            data: Object.keys(res["areaInfo"]).map((key) => {
                                return {
                                    value: res["areaInfo"][key],
                                    name: key,
                                };
                            }),
                        },
                    ],
                };
            });
    }
    openEditModal(item?): void {
        this.modalTitle = item ? `编辑巡检任务` : "新增巡检任务";
        this.fileList = item ? (this.fileList = this.fileList) : [];
        this.fileListVideo = item ? (this.fileListVideo = this.fileListVideo) : [];
        // this.fileUploadDisabled = !isEditable;
        if (item) {
            this.fetchService
                .get(`projectManage/xjTask/${item.taskid}`)
                .subscribe((resp) => {
                    this.checkForm.patchValue(resp);

                    console.log(resp);
                    if (resp["fileList"]) {
                        this.fileList = resp["fileList"].map((file) => {
                            return {
                                uid: file.id,
                                name: file.fileName,
                                url: `${(window as any).environment.apiBaseUrl}comm/file/view/${file.id
                                    }`,
                                status: "done",
                                type: file.contentType,
                            };
                        });
                    } else {
                        this.checkForm.patchValue({});
                    }
                });
        }
        this.modalShow = true;
    }

    onDelete(id) {
        this.fetchService
            .get(`projectManage/xjTask/remove/${id}`)
            .subscribe((resp) => {
                this.message.info("删除成功");
                this.queryInfo();
            });
    }

    onConfirm() {
        console.log(this.checkForm);
        if (!this.checkForm.valid) {
            this.message.warning("信息填写有误");
            return;
        }
        const data = {
            ...this.checkForm.value,
            begindate: this.checkForm.get("begindate").value
                ? moment(this.checkForm.get("begindate").value).format("YYYY-MM-DD")
                : null,
            enddate: this.checkForm.get("enddate").value
                ? moment(this.checkForm.get("enddate").value).format("YYYY-MM-DD")
                : null,
            fileIds: this.fileList
                .map((file) => {
                    if (file["response"]) {
                        return file.response.data.id;
                    } else {
                        return file.uid;
                    }
                })
                .join(","),
            vedioFileIds: this.fileListVideo
                .map((file) => {
                    if (file["response"]) {
                        return file.response.data.id;
                    } else {
                        return file.uid;
                    }
                })
                .join(","),
        };
        const url = data.taskid
            ? "projectManage/xjTask/edit"
            : "projectManage/xjTask/add";
        this.fetchService.post(url, data).subscribe((res) => {
            this.message.success("提交成功");
            this.modalShow = false;
            this.queryInfo();
            this.checkForm.reset();
        });
    }

    onCancel() {
        this.modalShow = false;
        this.checkForm.reset();
    }
    toView(data, type) {
        console.log(data, type);

        this.showType = type;

        this.fetchService
            .get(`projectManage/xjTask/${data.taskid}`)
            .subscribe((resp) => {
                if (type === 'typeImg') {
                    console.log(resp['fileList']);
                    if (resp['fileList'].length > 0) {
                        this.imgSrc =
                        "http://120.253.31.27:8082/api/comm/file/view/" +
                        resp["fileList"][0].id;
                        console.log(this.imgSrc);
                    }
                } else {
                    if (resp['vedioFileList'].length > 0) {
                        this.videoSrc =
                        "http://120.253.31.27:8082/api/comm/file/view/" +
                        resp["vedioFileList"][0].id;
                        console.log(this.videoSrc);
                    }

                }
                this.modalShowView = true;
            });




    }
    onCancelView() {
        this.imgSrc = "";
        this.videoSrc = "";
        this.modalShowView = false;
    }
    onConfirmView() {
        this.imgSrc = "";
        this.videoSrc = "";
        this.modalShowView = false;
    }
}
